//
//  accountViewController.swift
//  account
//
//  Created by Qingke on 16/4/25.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit
import CoreData
class accountViewController: UITableViewController {
    
    //MARK: -IBout 
    
    @IBOutlet weak var countTextField: UITextField!
    @IBOutlet weak var remarkTextField: UITextField!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var typeNameLabel: UILabel!

    @IBOutlet weak var outlayLabel: UILabel!
    @IBOutlet weak var incomeLabel: UILabel!
    
    // MARK: variable
    
    var appDel: AppDelegate!
    var context: NSManagedObjectContext!
    var id: Int?
    var dataModel: DataModel!
    var isIncome = false {
        didSet {
            //被改变前看一下自身状态，如果是false，就是outlayLabel 打对号
            if isIncome {
                incomeLabel.text = "√"
                outlayLabel.text = ""
            }else {
                incomeLabel.text = ""
                outlayLabel.text = "√"
            }
        }
    }
    let usdefault = NSUserDefaults.standardUserDefaults()

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        context = appDel.managedObjectContext
        dataModel = appDel.dataModel
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        if indexPath.row == 0 && indexPath.section == 1 {
            return indexPath
        } else {
            return nil
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("跳转到选择界面")
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toIcomTable" {
            let targetVc = segue.destinationViewController as! icomTableController
            targetVc.delegate = self
        }
    }
    
    //MARK：IBaction
    @IBAction func outlayButtonDown(sender: UIButton) {
        isIncome = false
    }
    @IBAction func incomeButtonDown(sender: UIButton) {
        isIncome = true
    }
    
    
    @IBAction func determine(sender: UIButton) {// 点击确定后，一系列动作
        dismissViewControllerAnimated(true, completion: nil)
        idNumber() //给id + 1
        var number = Double(countTextField.text!)
        if !isIncome {
            number = 0 - number!
        }
        dataModel.saveDataByCoreData(id ?? 0, number: number!, tip:remarkTextField.text! , itemName: typeNameLabel.text!)
        isOneDay()

    }
    
    func idNumber() {
        usdefault.setValue((id ?? 0) + 1 , forKey: "id")
        usdefault.synchronize()
    }
    
    func loadDauls() {
        id = usdefault.integerForKey("id")
    }
    
    func isOneDay() {
        // 获取当前系统时间的日期
        let time = NSDate()
        let nowCalender = getCalendar(time)
        let calendar = dataModel?.calendar // 获取最后一次操作时候的时间戳
        print(calendar)
        if let calendar1 = calendar , let _ = dataModel?.income ,let _ = dataModel?.outlay {
            if calendar1 == nowCalender
                // 让今天的时间戳，和 最后一次时间戳 进行对比。
            {   // 同一天的话就可以进行 累加，
                oneDaytotal()
    
            } else {
                usdefault.setObject(nowCalender, forKey: "Calendar")
                //不在同一天内，那么就把昨天的交易额 取出，累加，清零
                
                dataModel.monthIncome += dataModel.income
                dataModel.monthOutlay += dataModel.outlay
                dataModel.outlay = 0
                dataModel.income = 0
            }
            //不在同一个月，全部清零
            if chuliriqi(nowCalender) != chuliriqi(calendar!) {
                dataModel.monthOutlay = 0
                dataModel.monthIncome = 0
            }
            dataModel.saveData()
        }
    }
    
    func oneDaytotal() {
        if isIncome {
            dataModel.income += Double( countTextField.text!)!
        } else {
            dataModel.outlay += Double( countTextField.text!)!
        }

    }
    
    
    
    func getCalendar(now: NSDate) -> String{ // 获取今天的日期。
        let datef = NSDateFormatter()
        datef.dateStyle = .ShortStyle
        datef.timeStyle = .NoStyle
        let strdate = datef.stringFromDate(now)
        return strdate
    }
    
    //字符处理去掉前面的day 保留月 年
    func chuliriqi( str: String) -> String {
        let rangeOfstr = Range(start: str.endIndex.advancedBy(-4),
            end: str.endIndex)
        let s = str.substringWithRange(rangeOfstr)
        print(s)
        return s
    }
    
   
}
extension accountViewController: changeImageProtocol {
    func changeImage(UIControl: icomTableController, imageName: String) {
        imageView.image = UIImage(named: imageName)
        typeNameLabel.text = imageName
    }
}
   